//
//  MGNotificationManager.m
//  MortgageHelper
//
//  Created by fly Mac on 16/7/7.
//  Copyright © 2016年 zhangxiang. All rights reserved.
//

#import "ZXNotificationManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MGConstFile.h"
#import "AppDelegate.h"
#import "MGTipsViewController.h"


#define kDeviceToken @"ZX_JPUSH_SDK_DeviceToken"
#define kOnceAlertNotification @"kOnceAlertNotification"


#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>


#endif

static ZXNotificationManager *_sharedManger;

@interface ZXNotificationManager()<JPUSHRegisterDelegate>
@property (nonatomic,strong) NSString *deviceToken;
@property (nonatomic,strong)NSDictionary * userInfo;
@end

@implementation ZXNotificationManager
+(ZXNotificationManager *)sharedManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManger = [ZXNotificationManager new];
    });
    
    return _sharedManger;
}

/**
 *  从本地获取已保存的DeviceToken
 *
 *  @return deviceToken
 */
-(NSString *)getDeviceTokenFromLocal
{
    return [USER_DEFAULT objectForKey:kDeviceToken];
}

-(void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *token = [[[[deviceToken description]
                         stringByReplacingOccurrencesOfString:@"<" withString:@""]
                        stringByReplacingOccurrencesOfString:@">" withString:@""]
                       stringByReplacingOccurrencesOfString:@" " withString:@""];
    _deviceToken = token;
    [USER_DEFAULT setObject:token forKey:kDeviceToken];
    [USER_DEFAULT synchronize];
    
    [JPUSHService registerDeviceToken:deviceToken];
}

-(void)didReceiveLocalNotification:(UILocalNotification *)notification
{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    AudioServicesPlaySystemSound(1007);
}

-(void)registerUserNotification:(NSDictionary *)launchOptions
{
    [JPUSHService setupWithOption:launchOptions appKey:APP_KEY channel:CHANNEL apsForProduction:NO];
    
    //注册推送, iOS 10
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge | UNAuthorizationOptionSound;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
        });
        
#endif  
    }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
       
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    else {
        
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    
    if (launchOptions) {
        NSDictionary * remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        //这个判断是在程序没有运行的情况下收到通知，点击通知跳转页面
        if (remoteNotification) {
            NSLog(@"推送消息==== %@",remoteNotification);
            [self goToMssageViewControllerWith:remoteNotification];
        }
    }
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    
    NSDictionary * userInfo = notification.request.content.userInfo;
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        
        _sharedManger.userInfo=userInfo;
        WEAK_SELF
        MGTipsViewController * Vc=[MGTipsViewController viewWithSelfNib];
        Vc.tipsViewType=MGTipsViewTypeMessage;
        Vc.message_Lab.text=body?body:subtitle;
        [Vc customerUI];
        Vc.lookMessageBlock=^{
            STRONG_SELF
            [JPUSHService handleRemoteNotification:_sharedManger.userInfo];
            [strongSelf goToMssageViewControllerWith:_sharedManger.userInfo];

        };
        [KEY_WINDOW addSubview:Vc];
        [Vc mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(KEY_WINDOW).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
//    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

// 后台仍然在运行下 收到通知点击
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;

    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        

        [JPUSHService handleRemoteNotification:userInfo];
        [self goToMssageViewControllerWith:userInfo];
    }
    else {
        // 判断为本地通知
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

#pragma mark 通知点击跳转

- (void)goToMssageViewControllerWith:(NSDictionary*)msgDic{
    
    //将字段存入本地，因为要在你要跳转的页面用它来判断,这里我只介绍跳转一个页面，
//    type：<string>功能类型，1查档，2过户价，3评估价，4预约，5超值赎楼，6工行贷款，7民生贷款，8十成贷
//    id：<string>数据集id
//    url：<string>跳转的指定h5，没有则为空字符串，有则无视type规则，对url进行加载
    
    NSString *type = [msgDic valueForKey:@"type"];
    NSString *Id = [msgDic valueForKey:@"id"];
    NSString *url = [msgDic valueForKey:@"url"];
    
    NSLog(@"%@",msgDic);
//    if ([msgDic valueForKey:@"f"]) {
//
//        HChatClient *client = [HChatClient sharedClient];
//        if (client.isLoggedInBefore != YES) {
//            HError *error = [client loginWithUsername:ApplicationDelegate.name password:ApplicationDelegate.pwd];
//            if (!error) { //登录成功
//
//
//            } else { //登录失败
//                return;
//            }
//        }
//        // 进入会话页面
//        HDMessageViewController *chatVC = [[HDMessageViewController alloc] initWithConversationChatter:@"kefuchannelimid_500609"]; // 获取地址：kefu.easemob.com，“管理员模式 > 渠道管理 > 手机APP”页面的关联的“IM服务号”
//        [[self topViewController].navigationController pushViewController:chatVC animated:YES];
//        return;
//    }
//    if (!NULLString(url)) {
//        if (type.intValue == 4 || type.intValue == 6) {
//            //            推送地址：  需拼  userId  和  orderId     orderId   是id，不是订单编号
//            DiyadaiViewController * Vc=[[DiyadaiViewController alloc] initWithSelfClassNib];
//            Vc.url = url;
//            [[self topViewController].navigationController pushViewController:Vc animated:YES];
//            return;
//        }else if (type.intValue == 5)
//        {
//            TheLastEvaluateViewController * ctr = [[TheLastEvaluateViewController alloc]init];
//            ctr.url = url;
//            ctr.comefrom = @"noBulide";
//            [[self topViewController].navigationController pushViewController:ctr animated:YES];
//            return;
//        }
//        MGH5ViewController * VC = [[MGH5ViewController alloc] initWithSelfClassNib];
//        VC.h5Url = [msgDic objectForKey:@"url"];
//        [[self topViewController].navigationController pushViewController:VC animated:YES];
//        return;
//    }
//
//    switch (type.intValue) {
//        case 1:
//        {
//            if (!NULLString(Id)) {  //  1查档结果页
//                MGConsultFilesResultViewController *VC=[[MGConsultFilesResultViewController alloc] initWithSelfClassNib];
//                VC.ID=Id;
//                VC.toolEnumtype=ToolConsultTheFiles;
//                [[self topViewController].navigationController pushViewController:VC animated:YES];
//            }
//        }
//            break;
//        case 2:
//        {
//            if (!NULLString(Id)) {  //  2过户价结果页
//                MGConsultFilesResultViewController *VC=[[MGConsultFilesResultViewController alloc] initWithSelfClassNib];
//                VC.ID=Id;
//                VC.toolEnumtype=ToolTheTransferPrice;
//                [[self topViewController].navigationController pushViewController:VC animated:YES];
//
//            }
//        }
//            break;
//        case 3:
//        {
//            if (!NULLString(Id)) {  //  3评估价
//                MGConsultFilesResultViewController *VC=[[MGConsultFilesResultViewController alloc] initWithSelfClassNib];
//                VC.ID=Id;
//                VC.toolEnumtype=ToolFuturePrices;
//                [[self topViewController].navigationController pushViewController:VC animated:YES];
//
//            }
//        }
//            break;
//        case 7:
//        {
//            if (!NULLString(Id)) {
//                //审核
//                LzyBillOfLadingViewController * ctr = [[LzyBillOfLadingViewController alloc]init];
//                ctr.orderId = [Id integerValue];
//                [[self topViewController].navigationController pushViewController:ctr animated:YES];
//            }
//        }
//            break;
//        case 8:
//        {
//            if (!NULLString(Id)) {
//                //订单状态
//                LzyAppointmentResultViewController * ctr = [[LzyAppointmentResultViewController alloc]init];
//                ctr.orderId = [Id integerValue];
//                [[self topViewController].navigationController pushViewController:ctr animated:YES];
//            }
//        }
//            break;
//        default:
//            break;
//    }
}
- (UIViewController*)topViewController

{
    UIViewController *Vc=[self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    return Vc;
}


#pragma mark
- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
//        if ([rootViewController.presentedViewController isKindOfClass: [UIAlertController class]]) {
//            return rootViewController;
//        }
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}

-(NSString *)deviceToken
{
    if (!_deviceToken) {
        _deviceToken = [self getDeviceTokenFromLocal];
    }
    return _deviceToken;
}

-(BOOL )checkOnceAlertNotification:(UIViewController *)ViewController{
    BOOL isShow=NO;
    if (![USER_DEFAULT objectForKey:kOnceAlertNotification]) {
        
        BOOL isOpen=[Util isMessageNotificationServiceOpen];
        if (!isOpen) {
            MGTipsViewController * Vc=[MGTipsViewController viewWithSelfNib];
            Vc.tipsViewType=MGTipsViewTypeNoTiFy;
            [Vc customerUI];
            [KEY_WINDOW addSubview:Vc];
            [Vc mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(KEY_WINDOW).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
            }];
        }
    }else{
        isShow=YES;
    }
      [USER_DEFAULT setObject:kOnceAlertNotification forKey:kOnceAlertNotification];
      [USER_DEFAULT synchronize];
    
    return isShow;
}

@end
